// 考勤设置工具函数
import db from '../config/database.js'
import { getChinaTimeMinutes } from './timezone.js'

/**
 * 获取考勤设置
 * @returns {Promise<Object>} 考勤设置对象
 */
const getAttendanceSettings = async () => {
  try {
    const [rows] = await db.execute(
      'SELECT setting_name, setting_value FROM attendance_settings'
    )
    
    // 转换为对象格式
    const settings = {}
    rows.forEach(row => {
      settings[row.setting_name] = row.setting_value
    })
    
    // 设置默认值（如果数据库中没有对应设置）
    return {
      arrival_time: settings.arrival_time || '08:45:00',
      departure_time: settings.departure_time || '17:30:00',
      modification_limit_time: settings.modification_limit_time || '14:00:00'
    }
  } catch (error) {
    console.error('获取考勤设置失败:', error)
    // 返回默认设置
    return {
      arrival_time: '08:45:00',
      departure_time: '17:30:00',
      modification_limit_time: '14:00:00'
    }
  }
}

/**
 * 获取单个考勤设置值
 * @param {string} settingName - 设置名称
 * @returns {Promise<string>} 设置值
 */
const getAttendanceSetting = async (settingName) => {
  try {
    const [rows] = await db.execute(
      'SELECT setting_value FROM attendance_settings WHERE setting_name = ?',
      [settingName]
    )
    
    if (rows.length > 0) {
      return rows[0].setting_value
    }
    
    // 返回默认值
    const defaults = {
      arrival_time: '08:45:00',
      departure_time: '17:30:00',
      modification_limit_time: '14:00:00'
    }
    
    return defaults[settingName] || null
  } catch (error) {
    console.error('获取考勤设置失败:', error)
    return null
  }
}

/**
 * 检查当前时间是否超过入园时间
 * @returns {Promise<boolean>} 是否超过入园时间
 */
const isAfterArrivalTime = async () => {
  try {
    const arrivalTime = await getAttendanceSetting('arrival_time')
    const currentTime = getChinaTimeMinutes() // 使用中国时区
    
    // 解析入园时间
    const [hours, minutes] = arrivalTime.split(':').map(Number)
    const arrivalMinutes = hours * 60 + minutes
    
    return currentTime > arrivalMinutes
  } catch (error) {
    console.error('检查入园时间失败:', error)
    return false
  }
}

/**
 * 检查当前时间是否超过限制标记时间
 * @returns {Promise<boolean>} 是否超过限制标记时间
 */
const isAfterModificationLimit = async () => {
  try {
    const limitTime = await getAttendanceSetting('modification_limit_time')
    const currentTime = getChinaTimeMinutes() // 使用中国时区
    
    // 解析限制时间
    const [hours, minutes] = limitTime.split(':').map(Number)
    const limitMinutes = hours * 60 + minutes
    
    return currentTime >= limitMinutes
  } catch (error) {
    console.error('检查限制标记时间失败:', error)
    return false
  }
}

/**
 * 将时间字符串转换为分钟数
 * @param {string} timeStr - 时间字符串 (HH:MM:SS 或 HH:MM)
 * @returns {number} 分钟数
 */
const timeToMinutes = (timeStr) => {
  const [hours, minutes] = timeStr.split(':').map(Number)
  return hours * 60 + minutes
}

export {
  getAttendanceSettings,
  getAttendanceSetting,
  isAfterArrivalTime,
  isAfterModificationLimit,
  timeToMinutes
}